<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1432.0.js"></script>
  <script>
      const getParams =  (filename, cb) => {
          fetch("/api/tempUrl/", {
              method: "POST",
              headers: {
                "Content-Type": "application/json" // 指定请求头中的内容类型为JSON
              },
              body:JSON.stringify({
                  filename,
              }),
          }).then(resp => resp.text())
              .then(data => cb(data));
      };

      const uploadFile = () =>{
          let fileInput = document.getElementById("sample_file");
          let fileName = fileInput.files[0].name;
          console.log(fileName);
          // 第一步, 拿到授权url
          getParams(fileName, url => {
              console.log(url);
              // 第二步, 向oss 上传文件
              fetch (url, {
                method: 'PUT',
                body: fileInput.files[0]
              })
                .then (response => response.text()) // 如果响应是一个JSON对象，就解析它
                .then (data => {
                    console.log ("upload to oss success");
                    console.log(data);
                    // 第三部, 调用接口, 注册文件
                    fetch("/api/registFile/", {
                        method: "POST",
                        headers: {
                          "Content-Type": "application/json" // 指定请求头中的内容类型为JSON
                        },
                        body:JSON.stringify({
                            filename: fileName,
                        }),
                    }).then(resp => resp.json())
                    .then(data => {
                        console.log("regist file success");
                        console.log(data);
                    });
                }) // 处理成功的响应对象
                .catch (error => console.log (error)); // 处理错误的响应对象

          });
      };



  </script>

</head>
<body>
<form method="post" id="upload_file" action="" enctype="multipart/form-data">
  文件:
  <input type="file" id="sample_file" name="sample_file">
  <button type="button" onclick="uploadFile();">提交</button>
</form>
<br>
<p>{{message}}</p>
<div>
  {% for attachment in attachments %}
    <a href="/api/getFile/?id={{attachment.id}}">{{attachment.title}}</a>
  {% endfor %}
</div>

</body>
</html>